import { defineStore } from 'pinia';
import Cookies from 'js-cookie';
import { Session } from '/@/utils/storage';
import { useTeacherApi } from '/@/api/teacher';

/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
export const useUserInfo = defineStore('userInfo', {
	state: (): UserInfosState => ({
		userInfos: {
			id: '',
			userName: '',
			photo: '',
			time: 0,
			roles: [],
			authBtnList: [],
			dept_id: '',
			dept_name: '',
			role_id: '',
			role_name: '',
			teacher_name: ''
		},
	}),
	actions: {
		async setUserInfos() {
			// 存储用户信息到浏览器缓存
			if (Session.get('userInfo')) {
				this.userInfos = Session.get('userInfo');
			} else {
				const userInfos = <UserInfos>await this.getApiUserInfo();
				this.userInfos = userInfos;
			}
		},
		// 模拟接口数据
		// https://gitee.com/lyt-top/vue-next-admin/issues/I5F1HP
		async getApiUserInfo() {
			return new Promise((resolve) => {
				setTimeout(() => {
					// 模拟数据，请求接口时，记得删除多余代码及对应依赖的引入
					// const userName = Cookies.get('userName');
					useTeacherApi().getTeacherUserData({ id: Cookies.get('teacher_id') }).
						then(async (res) => {
							console.log(`用户信息:`, res);
							// 用户信息数据
							const userInfos = {
								id: res.data.id,
								userName: res.data.username,
								photo:
									res.data.username === 'admin'
										? 'https://img2.baidu.com/it/u=1978192862,2048448374&fm=253&fmt=auto&app=138&f=JPEG?w=504&h=500'
										: 'https://img2.baidu.com/it/u=2370931438,70387529&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500',
								time: new Date().getTime(),
								roles: [res.data.mark],  //角色
								dept_id: res.data.dept_id,
								dept_name: res.data.dept_name,
								role_id: res.data.role_id,
								role_name: res.data.role_name,
								teacher_name: res.data.teacher_name
							};
							Session.set('userInfo', userInfos);
							resolve(userInfos);
						})
				}, 0);
			});
		},
	},
});
